package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.wemedia.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Autowired
    GeneratePageService generatePageService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 文章定时发布功能实现
     *
     * @param newsId 文章id
     */
    @GlobalTransactional(rollbackFor = Exception.class, timeoutMills = 100000)
    @Override
    public void publishArticle(Integer newsId) {
        //查询并校验自媒体文章
        WmNews wmNews = getWmNews(newsId);
        //基于自媒体文章 封装ApArticle
        ApArticle article = getApArticle(wmNews);
        //保存或修改article
        saveOrUpdateArticle(article);
        //保存artic_config 和artic_content信息
        saveConfigAndContent(wmNews, article);
        // 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),article);
        //更新wmNews状态 为9 设置关联的articleId
        updateWmNews(wmNews, newsId, article);
        // 通知es索引库增加文章
        redisTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,article.getId());
        log.info("文章发布成功  通知索引库增加文章成功 文章id {}",article.getId());

    }

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Value("${file.minio.readPath}")
    String readPath;

    /**加载文章列表
     *
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
          //设置每页大小
        //检查参数
        Integer size = dto.getSize();
        if(size==null||size<=0){
            size=10;
        }
        dto.setSize(size);
        //设置默认频道
        if(StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //设置时间(最大 最小)
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //设置类型
        //不加载最新  也不加载更多 就默认为加载 更多
        if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)&&!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)){
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //调用mapper 查询数据库
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);

        for (ApArticle apArticle : apArticles) {
            apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }
        //结果封装
        ResponseResult result = ResponseResult.okResult(apArticles);
        result.setHost(webSite);
        return result;
    }

    /**根据参数加载文章列表
     *
     * @param loadtypeLoadMore
     * @param dto
     * @param firstPage
     * @return
     */
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDTO dto, boolean firstPage) {
        if(firstPage){
            //查询redis缓存文章
            String articleListJson = (String) redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(articleListJson)){
                //将json集合 转为list集合泛型为ApArticle
                List<ApArticle> apArticles = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
                }
                ResponseResult result = ResponseResult.okResult(apArticles);
                result.setHost(webSite);
                return result;
            }
        }

        return load(loadtypeLoadMore,dto);
    }


    /**
     * 更新wmNews状态 为9 设置关联的articleId
     *
     * @param wmNews
     * @param newsId
     * @param article
     */
    private void updateWmNews(WmNews wmNews, Integer newsId, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        //远程调用接口 更新文章状态
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()) {
            log.error("文章发布失败 远程调用出现问题 文章id为{}:", newsId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }

    }

    /**
     * 保存artic_config 和artic_content信息方法实现
     *
     * @param wmNews
     * @param article
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle article) {
        //保存artic_config信息
        ApArticleConfig articleConfig = new ApArticleConfig();
        //文章id
        articleConfig.setArticleId(article.getId());
        //是否可评论
        articleConfig.setIsComment(true);
        //是否可转发
        articleConfig.setIsForward(true);
        //是否已删除
        articleConfig.setIsDelete(false);
        //是否下架
        articleConfig.setIsDown(false);
        //保存
        apArticleConfigMapper.insert(articleConfig);
        ApArticleContent apArticleContent = new ApArticleContent();
        //文章id
        apArticleContent.setArticleId(article.getId());
        //文章内容
        apArticleContent.setContent(wmNews.getContent());
        //保存
        apArticleContentMapper.insert(apArticleContent);

    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;


    /**
     * 保存或修改文章方法实现
     *
     * @param article
     */
    private void saveOrUpdateArticle(ApArticle article) {
        //判断是否有文章id  如果没有证明需要保存  反之需要修改
        if (article.getId() == null) {
            //保存文章  设置属性
            //点赞数
            article.setLikes(0);
            //收藏数
            article.setCollection(0);
            //评论数量
            article.setComment(0);
            //阅读数
            article.setViews(0);
            //保存
            save(article);
        } else {
            //更新文章
            updateById(article);
            //删除关联关系
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, article.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));

        }

    }

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private AuthorMapper authorMapper;

    /**
     * 封装ApArticle
     *
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle article = new ApArticle();
        //拷贝属性
        BeanUtils.copyProperties(wmNews, article);
        //文章属性
        article.setFlag((byte) 0);
        //设置文章布局
        article.setLayout(wmNews.getType());
        //设置文章id
        article.setId(wmNews.getArticleId());
        //设置频道信息  远程查询
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        //判断远程接口调用是否成功
        if (!channelResult.checkCode()) {
            log.error("文章发布失败,远程调用频道查询接口失败 频道id{}:", wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        //获取频道信息
        AdChannel channel = channelResult.getData();
        if (channel == null) {
            log.error("文章发布失败,查询不到该频道 频道id{}:", wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //将频道信息设置到app端文章表中
        article.setChannelId(wmNews.getChannelId());
        article.setChannelName(channel.getName());
        //设置作者信息
        //先查询出作者信息
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        //判断作者是否存在
        if (author == null) {
            log.error("文章发布失败,查询不到该文章作者信息");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询不到作者信息");
        }
        article.setAuthorId(Long.valueOf(author.getId()));
        article.setAuthorName(author.getName());
        //返回结果
        return article;
    }

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 查询并校验文章
     *
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        //调用远程feigin接口 根据id查询文章
        ResponseResult<WmNews> wmNewsResult = wemediaFeign.findWmNewsById(newsId);
        //数据检查
        if (!wmNewsResult.checkCode()) {
            log.error("文章发布失败,远程调用接口失败 文章id{}:", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "远程调用接口失败 请重新尝试");
        }
        //获取文章信息
        WmNews wmNews = wmNewsResult.getData();
        //判断文章是否存在
        if (wmNews == null) {
            log.error("文章发布失败 查询不到文章信息");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //判断文章状态是否为 4 或 8 待发布状态
        short status = wmNews.getStatus().shortValue();
        if (status != WmNews.Status.ADMIN_SUCCESS.getCode() && status != WmNews.Status.SUCCESS.getCode()) {
            log.error("文章发布失败 当前文章不是待发布状态");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章不是待发布状态");
        }
        //返回文章内容
        return wmNews;
    }
}